package com.zys.sac.core.filter;

import com.zys.sac.core.constant.RequestParam;
import com.zys.sac.core.constant.RequestStatus;
import com.zys.sac.core.util.ServletResponseUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhongjunkai on 2022/3/31.
 */
public class SessionCheckFilter extends SacCheckFilter{

    private String loginPath;

    public SessionCheckFilter(String loginPath) {
        this.loginPath = loginPath;
    }

    @Override
    public String loginPath() {
        return loginPath;
    }

    @Override
    protected boolean doCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication == null ? null : authentication.getPrincipal();
        if(null == principal) {
            ServletResponseUtils.render(response, ServletResponseUtils.result(RequestStatus.USEREMPTY.getCode(), RequestStatus.USEREMPTY.getMsg()));
            return false;
        } else {
            List<String> authorities = (List<String>)session.getAttribute(RequestParam.AUTHORITIES);
            List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
            authorities.stream().forEach(auth -> authorityList.add(new SimpleGrantedAuthority(auth)));
            // 这里将权限和角色交给权限交给SpringSecurity容器进行管理，后续的SpringSecurity验证过滤器会自动对权限进行过滤，无需自己手动过滤
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(principal, null, authorityList);
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            return true;
        }
    }
}
